<template>
  <div class="team-setting">
    <template v-if="showPage">
      <div class="page-center">
        <a-page-header
          title="团队管理"
          @back="() => $router.back()"
          style="padding: 10px 0"
        />
        <div class="content beauty-scroller-bar">
          <template v-if="notMember">
            <a-card :bordered="false" style="border-radius: 6px">
              <div class="flex flex-col align-center py-30">
                <WarningFilled style="color: #faad14; font-size: 64px" />
                <div class="mt-20 fs-24">此能力仅 团队/企业 成员可用</div>
                <div class="mt-10 text-gray-6">当前身份：个人</div>
                <a-row class="mt-20 flex justify-center">
                  <a-button
                    type="primary"
                    style="border-radius: 6px"
                    @click="showMemberVisible = true"
                  >
                    <template #icon><SwapOutlined /></template>
                    切换 团队/企业
                  </a-button>
                  <a-button
                    type="primary"
                    class="ml-20"
                    style="border-radius: 6px"
                    @click="addTeamVisible = true"
                  >
                    <template #icon><PlusCircleOutlined /></template>
                    创建 团队/企业
                  </a-button>
                </a-row>
              </div>
            </a-card>
          </template>
          <template v-else>
            <a-card
              :bordered="false"
              style="border-radius: 6px"
              :bodyStyle="{ display: 'flex' }"
            >
              <div class="left">
                <div
                  class="tab-item"
                  :class="currentTab == 'info' ? 'tab-item-current' : ''"
                  @click="onLeftTabChange('info')"
                >
                  基本信息
                </div>
                <div
                  class="tab-item"
                  :class="currentTab == 'list' ? 'tab-item-current' : ''"
                  @click="onLeftTabChange('list')"
                >
                  成员管理
                </div>
                <div
                  class="tab-item"
                  :class="currentTab == 'wiki' ? 'tab-item-current' : ''"
                  @click="onLeftTabChange('wiki')"
                >
                  知识库
                </div>
              </div>
              <div class="right">
                <template v-if="currentTab == 'info'">
                  <a-form
                    :model="formRef"
                    layout="vertical"
                    style="width: 400px"
                  >
                    <a-form-item label="团队名称" v-bind="validateInfos.name">
                      <a-input
                        v-model:value="formRef.name"
                        placeholder="请输入"
                      />
                    </a-form-item>
                    <a-form-item label="团队简介" v-bind="validateInfos.intro">
                      <a-input
                        v-model:value="formRef.intro"
                        placeholder="一句话介绍"
                      />
                    </a-form-item>
                    <a-form-item label="团队图标" v-bind="validateInfos.avatar">
                      <a-upload
                        :action="$utils.imgAction"
                        :headers="{ 'org-token': $store.getters.token }"
                        v-model:file-list="fileList"
                        @change="handleUploadChange"
                        :multiple="true"
                        name="image"
                        :data="{ dir: 'work_ai' }"
                        accept="image/*"
                        list-type="picture-card"
                      >
                        <div v-if="!fileList.length">
                          <plus-outlined />
                          <div>上传图片</div>
                        </div>
                      </a-upload>
                    </a-form-item>
                  </a-form>
                  <a-button
                    type="primary"
                    @click="onSubmit"
                    style="margin-left: 10px"
                    >保存</a-button
                  >
                  <div class="flex" style="margin-top: 100px">
                    <div>
                      <p>剩余对话次数</p>
                      <p style="font-size: 18px; font-weight: 700">
                        {{
                          formRef.total_numbers > 100000
                            ? "100000+"
                            : formRef.total_numbers
                        }}
                      </p>
                    </div>
                    <div style="margin-left: 100px">
                      <p>剩余绘画次数</p>
                      <p style="font-size: 18px; font-weight: 700">
                        {{
                          formRef.total_art_numbers > 100000
                            ? "100000+"
                            : formRef.total_art_numbers
                        }}
                      </p>
                    </div>
                  </div>
                </template>
                <template v-if="currentTab == 'wiki'">
                  <a-form :model="formRef" layout="vertical" style="width: 50%">
                    <a-form-item
                      label="知识库查询"
                      v-bind="validateInfos.use_wiki"
                    >
                      <a-switch
                        checked-children="开"
                        un-checked-children="关"
                        :checkedValue="1"
                        :unCheckedValue="0"
                        v-model:checked="formRef.use_wiki"
                      />
                    </a-form-item>
                    <a-form-item
                      label="搜索模式"
                      v-bind="validateInfos.wiki_search_mode"
                    >
                      <a-select
                        v-model:value="formRef.wiki_search_mode"
                        style="width: 250px"
                      >
                        <a-select-option :value="1"
                          >高相似度，无匹配时拒绝回复</a-select-option
                        >
                        <a-select-option :value="2"
                          >高相似度，无匹配时直接回复</a-select-option
                        >
                        <a-select-option :value="3"
                          >低相似度匹配</a-select-option
                        >
                      </a-select>
                    </a-form-item>
                    <a-form-item
                      label="系统提示词"
                      v-bind="validateInfos.system_prompt"
                    >
                      <a-textarea
                        v-model:value="formRef.system_prompt"
                        placeholder="模型默认的提示词，通过调整该内容，可以引导模型聊天方向。"
                        :rows="4"
                      />
                    </a-form-item>
                    <a-form-item label="对接Token" v-bind="validateInfos.token">
                      <a-input
                        v-model:value="formRef.token"
                        placeholder="不填写则自动创建"
                      />
                    </a-form-item>
                  </a-form>
                  <a-button
                    type="primary"
                    @click="onSubmit"
                    style="margin-left: 10px"
                    >保存</a-button
                  >
                </template>
                <template v-if="currentTab == 'list'">
                  <a-tabs v-model:activeKey="currentTableTab" @change="getList">
                    <a-tab-pane :key="-1" :tab="tab1"></a-tab-pane>
                    <a-tab-pane :key="0" :tab="tab2"></a-tab-pane>
                    <template #tabBarExtraContent>
                      <a-button
                        type="primary"
                        class="ml-20"
                        style="border-radius: 6px"
                        @click="inviteMemberVisible = true"
                      >
                        <template #icon><UserAddOutlined /></template>
                        邀请成员
                      </a-button>
                    </template>
                  </a-tabs>
                  <a-table
                    :dataSource="dataSource"
                    :columns="columns"
                    :pagination="pagination"
                    @change="handleTableChange"
                    rowKey="id"
                    :bordered="true"
                    size="small"
                  >
                    <template #user="{ record }">
                      <div style="display: flex; align-items: center">
                        <img
                          :src="record.avatar"
                          alt=""
                          v-if="record.avatar"
                          style="
                            width: 32px;
                            height: 32px;
                            border-radius: 4px;
                            object-fit: cover;
                            cursor: pointer;
                          "
                          @click.stop="openUrl(record.avatar)"
                        />
                        <span
                          v-else
                          style="
                            width: 32px;
                            height: 32px;
                            border-radius: 4px;
                            background-color: #f1f1f1;
                            display: inline-block;
                          "
                        ></span>
                        <span style="margin-left: 10px">{{
                          record.nickname || "--"
                        }}</span>
                      </div>
                    </template>
                    <template #phone="{ text }">
                      <span>{{ text || "--" }}</span>
                    </template>

                    <template #action="{ record }">
                      <template v-if="isAdmin">
                        <template v-if="record.status == 0">
                          <a-button
                            type="link"
                            style="padding: 0; margin: 0; color: #52c41a"
                            @click.stop="editClick(record.id, 1)"
                            >同意</a-button
                          >
                          <a-button
                            type="link"
                            danger
                            style="
                              padding: 0;
                              margin-right: 0;
                              margin-left: 10px;
                            "
                            @click.stop="editClick(record.id, 4)"
                            >删除</a-button
                          >
                        </template>
                        <template
                          v-if="record.status == 1 && !record.is_creator"
                        >
                          <a-button
                            type="link"
                            danger
                            style="padding: 0; margin-right: 0"
                            @click.stop="deleteClick(record.id)"
                            >移除</a-button
                          >
                        </template>
                        <template v-else>-</template>
                      </template>
                      <template v-else>-</template>
                    </template>
                  </a-table>
                </template>
              </div>
            </a-card>
          </template>
        </div>
      </div>
    </template>

    <!-- 切换团队、企业 -->
    <a-modal
      :title="'选择' + (showMemberBusiness ? '企业' : '团队')"
      :width="500"
      :visible="showMemberVisible"
      @cancel="showMemberVisible = false"
      :footer="false"
      centered
      :zIndex="1002"
    >
      <team-slider
        @addTeam="addTeamCallback"
        :team="showMemberTeam"
        :business="showMemberBusiness"
        height="400px"
        @change="onTeamChange"
      ></team-slider>
    </a-modal>

    <AddTeam
      :visible="addTeamVisible"
      @onClose="addTeamVisible = false"
      @success="addTeamSuccess"
    />

    <InviteMember
      :visible="inviteMemberVisible"
      @onClose="inviteMemberVisible = false"
    />

    <LoginModal
      :visible="loginVisible"
      @onClose="loginVisible = false"
      @loginCallback="loginCallback"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  h,
  onBeforeUnmount,
  createVNode,
  ref,
  nextTick,
  inject,
} from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Form, Modal, notification, message } from "ant-design-vue";
import {
  WarningFilled,
  SwapOutlined,
  PlusCircleOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  UserAddOutlined,
} from "@ant-design/icons-vue";
import AddTeam from "../../components/AddTeam/index.vue";
import InviteMember from "../../components/InviteMember/index.vue";
import TeamSlider from "@/components/TeamSlider/index.vue";

const useForm = Form.useForm;
export default defineComponent({
  name: "TeamSetting",
  components: {
    WarningFilled,
    SwapOutlined,
    PlusCircleOutlined,
    AddTeam,
    PlusOutlined,
    UserAddOutlined,
    InviteMember,
    TeamSlider,
  },

  setup() {
    const route = useRoute();
    const router = useRouter();

    const state = reactive({
      notMember: false,

      addTeamVisible: false,
      currentTab: "info",
      fileList: [],

      page: 1,
      pageSize: 10,
      total: 0,
      dataSource: [],
      columns: [
        {
          title: "用户",
          slots: {
            customRender: "user",
          },
          width: "20%",
        },
        {
          title: "手机号码",
          dataIndex: "phone",
          slots: {
            customRender: "phone",
          },
          width: "20%",
        },
        {
          title: "加入时间",
          dataIndex: "created_at",
          slots: {
            customRender: "created_at",
          },
          width: "15%",
        },
        {
          title: "操作",
          slots: {
            customRender: "action",
          },
          width: "10%",
          align: "center",
        },
      ],

      isAdmin: false,
      tab1: "全部（0）",
      tab2: "待审批（0）",
      currentTableTab: -1,
      inviteMemberVisible: false,
      loginVisible: false,
      showPage: false,

      showMemberVisible: false,
      isBusiness: 0,
      showMemberTeam: true,
      showMemberBusiness: true,
    });

    const formRef = reactive({
      name: "",
      intro: "",
      avatar: "",
      token: "",
      use_wiki: 0,
      wiki_search_mode: 1,
      system_prompt: "",
      total_numbers: 0,
      total_art_numbers: 0,
    });

    const rulesRef = reactive({
      name: [{ required: true, message: "团队名称不能为空" }],
    });

    const { resetFields, validate, validateInfos } = useForm(formRef, rulesRef);

    const getTeamDetail = () => {
      state.fileList = [];
      resetFields();
      request
        .get("/work_ai", "/user/team", {
          id: store.state.user.teamId,
        })
        .then((res) => {
          if (res.detail) {
            for (let key in formRef) {
              formRef[key] = res.detail[key];
            }
            if (res.detail.avatar) {
              state.fileList.push({
                uid: 1,
                name: res.detail.avatar,
                status: "done",
                url: res.detail.avatar,
              });
            }
          }
        });
    };

    const addTeamSuccess = () => {
      state.addTeamVisible = false;
      init();
    };

    const onLeftTabChange = (tab) => {
      if (state.currentTab == tab) {
        return;
      }
      state.currentTab = tab;
    };

    // 上传图片
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList.map((file, index) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              message.warning(file.response.msg);
              resFileList.splice(index, 1);
            }
          }
        });
      }
      state.fileList = resFileList;
      if (state.fileList.length) {
        formRef.avatar = state.fileList[0].url;
      } else {
        formRef.avatar = "";
      }
    };

    const onSubmit = () => {
      validate().then(() => {
        let params = {
          id: store.state.user.teamId,
        };
        for (let key in formRef) {
          params[key] = formRef[key];
        }
        request
          .put("/work_ai", "/user/team", {
            ...params,
          })
          .then((res) => {
            message.success("保存成功");
          });
      });
    };

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showSizeChanger: true,
    }));

    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      getList();
    };

    const getList = () => {
      let params = {
        page: state.page,
        pageSize: state.pageSize,
        team_id: store.state.user.teamId,
      };
      if (state.currentTableTab >= 0) {
        params.status = state.currentTableTab;
      }
      request
        .get("/work_ai", "/user/team/user/list", { ...params })
        .then((res) => {
          if (res.list && res.list.data) {
            state.dataSource = res.list.data;
          }
          state.total = res.total;
          if (res.team && res.team.can_edit) {
            state.isAdmin = true;
          } else {
            state.isAdmin = false;
          }
          if (res.count) {
            state.tab1 = `全部（${res.count.all}）`;
            state.tab2 = `待审批（${res.count.approval}）`;
          }
        });
    };

    // 操作：同意、拒绝
    const editClick = (id, status) => {
      request
        .put("/work_ai", "/user/team/user", {
          id,
          status,
        })
        .then((res) => {
          message.success("操作成功");
          state.page = 1;
          getList();
        });
    };

    // 删除
    const deleteClick = (id) => {
      Modal.confirm({
        title: () => `确定要移除吗？`,
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          request
            .del("/work_ai", "/user/team/user", {
              id,
            })
            .then((res) => {
              message.success("删除成功");
              state.page = 1;
              getList();
            });
        },
      });
    };

    const init = () => {
      utils.checkLogin().then((isLogin) => {
        if (!isLogin) {
          state.loginVisible = true;
          return;
        }
        state.showPage = true;
        if (store.state.user.teamId) {
          state.notMember = false;
          getTeamDetail();
          getList();
        } else {
          state.notMember = true;
        }
      });
    };

    init();

    watch(
      () => store.state.user.teamId,
      (val) => {
        init();
      }
    );

    const loginCallback = () => {
      state.loginVisible = false;
      router.go(0);
    };

    const addTeamCallback = (is_business) => {
      state.addTeamVisible = true;
      state.isBusiness = is_business;
    };

    const onTeamChange = (team) => {
      state.showMemberVisible = false;
    };

    return {
      ...toRefs(state),
      addTeamSuccess,
      validateInfos,
      formRef,
      onLeftTabChange,
      handleUploadChange,
      onSubmit,

      pagination,
      handleTableChange,
      getList,
      editClick,
      deleteClick,

      loginCallback,
      addTeamCallback,
      onTeamChange,
    };
  },
});
</script>

<style lang="less" scoped>
.team-setting {
  width: 100%;
  height: 100%;

  .page-center {
    margin: 0 auto;
    max-width: 1200px;

    .content {
      width: 100%;
      height: calc(100% - 60px);
      overflow: hidden auto;

      .left {
        width: 200px;
        border-right: 1px solid #f5f5f5;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding-right: 20px;

        .tab-item {
          width: 120px;
          height: 40px;
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;
          border-radius: 8px;
          margin-bottom: 10px;

          &:hover {
            background-color: #f5f5f5;
          }
        }

        .tab-item-current {
          background-color: #f3f0ff;
          color: #5a54f9;

          &:hover {
            background-color: #f3f0ff;
          }
        }
      }

      .right {
        flex: 1;
        padding-left: 60px;
      }
    }
  }
}
</style>
